package com.ruike.alisurface.ui.answerQuestion.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.ui.answerQuestion.bean.QuestionBean;

import java.util.List;

/**
 * Author: voodoo
 * CreateDate: 2023/11/20 020下午 03:13
 * Description: 选项适配器
 */
public class QuestionOptionAdapter extends RecyclerView.Adapter<QuestionOptionAdapter.QuestionOptionViewHolder> {

    Context context;
    List<QuestionBean.OptionsBean> list;
    boolean isSingle;

    public QuestionOptionAdapter(Context context, List<QuestionBean.OptionsBean> list, boolean isSingle) {
        this.context = context;
        this.list = list;
        this.isSingle = isSingle;
    }

    public void setList(List<QuestionBean.OptionsBean> list){
        this.list = list;
        notifyDataSetChanged();
    }

    public List<QuestionBean.OptionsBean> getList(){
        return list;
    }

    @NonNull
    @Override
    public QuestionOptionViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_question_option, viewGroup, false);
        return new QuestionOptionViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull QuestionOptionViewHolder viewHolder, int i) {
        QuestionBean.OptionsBean optionsBean = list.get(i);
        viewHolder.conLayout.setSelected(optionsBean.isSelect());
        viewHolder.optionTv.setText(optionsBean.getOption_content());

        int type = optionsBean.getType();
        if (type != 0) {
            viewHolder.conLayout.setBackgroundResource(type > 0 ? R.drawable.shape_answer_success : R.drawable.shape_answer_error);
        }

        viewHolder.itemView.setOnClickListener(view -> {
            if (isSingle) {
                // 如果是单选，则先清空之前选择的项
                for (QuestionBean.OptionsBean bean : list) {
                    bean.setSelect(false);
                }
            }
            optionsBean.setSelect(!optionsBean.isSelect());
            list.set(i, optionsBean);
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public class QuestionOptionViewHolder extends RecyclerView.ViewHolder {

        ConstraintLayout conLayout;
        TextView optionTv;

        public QuestionOptionViewHolder(@NonNull View itemView) {
            super(itemView);
            conLayout = itemView.findViewById(R.id.itemQuestionOption_root_cl);
            optionTv = itemView.findViewById(R.id.itemQuestionOption_option_tv);
        }
    }

}
